package com.handydata.antifraud.channel.outshbank;


import com.handydata.antifraud.bo.orderbaseinfo.OrderBaseInfoReqBO;
import com.handydata.antifraud.channel.outbound.RiskResultSendBack;
import com.handydata.antifraud.enums.OperateTypeEnum;
import com.handydata.antifraud.retry.RetryExecutor;
import com.handydata.antifraud.service.RiskResultProcessService;
import com.handydata.antifraud.vo.riskres.RiskOutputVO;
import com.handydata.common.convert.CommonBeanConvertor;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class RabbitSenfBankReceiver {

    @Autowired
    private RetryExecutor retryExecutor;


    @Autowired
    private RiskResultSendBack riskResultSendback;

    @Autowired
    private RiskResultProcessService riskResultProcessService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "shBankInfo",
                    durable="true"),
            exchange = @Exchange(value = "exchange-3",
                    durable="true",
                    type= "fanout",
                    ignoreDeclarationExceptions = "true"),
            key = {"info","error","warning"}
    )
    )
    @RabbitHandler
    public void onMessage(Message<?> message, Channel channel) throws Exception {
        log.info("接收队列shBankInfo数据开始处理{},{}",channel.getChannelNumber(),this.hashCode());
        Long deliveryTag = (Long)message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
        try {
            RiskOutputVO riskOutputVO = (RiskOutputVO) message.getPayload();
            if(Objects.isNull(riskOutputVO)){
                log.info("接收队列shBankInfo数据有问题:riskOutputVO=null");
                channel.basicAck(deliveryTag, false);
                return;
            }
            log.info("接收队列shBankInfo数据:{}",riskOutputVO.toString());
            OrderBaseInfoReqBO reqBO = CommonBeanConvertor.convert(riskOutputVO, OrderBaseInfoReqBO.class);
            reqBO.setSendMsg(riskOutputVO.getJSONString());
            retryExecutor.doRetry(
                    () -> riskResultSendback.doAction(riskOutputVO),
                    comment -> {
                        reqBO.setProcessState(comment.getCode());
                        riskResultProcessService.process(reqBO, OperateTypeEnum.PUSH);
                    }
            );
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            e.printStackTrace();
            log.error("发送上行数据异常:{}",e);
            channel.basicAck(deliveryTag, false);
        }
    }
}